package com.kaka.bus.engine.borrow.bank;

import android.support.v7.widget.AppCompatButton;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.jakewharton.rxbinding.view.RxView;
import com.kaka.bus.AppCenter;
import com.kaka.bus.R;
import com.kaka.bus.base.BaseActivity;
import com.kaka.bus.bean.BankBean;
import com.kaka.bus.bean.HttpWrapper;
import com.kaka.bus.bean.NamePhoneBean;
import com.kaka.bus.bean.Single;
import com.kaka.bus.constant.Constant;
import com.kaka.bus.constant.UserConstant;
import com.kaka.bus.engine.other.DrainageActivity;
import com.kaka.bus.manager.BottomDialogManager;
import com.kaka.bus.util.U;
import com.kaka.bus.util.logger.Logger;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;

/**
 * Created by zhangqi on 2016/10/19.
 * e-mail : ${email}
 * desc :
 */

public class BankCardActivity extends BaseActivity<BankCardPresenter> implements BackCardContract.View {

    @BindView(R.id.toolbar_back)
    ImageView mToolbarBack;
    @BindView(R.id.toolbar_name)
    TextView mToolbarName;
    @BindView(R.id.toolbar)
    Toolbar mToolbar;
    @BindView(R.id.tv_bank_tips)
    TextView mTvBankTips;
    @BindView(R.id.tv_bank_personname)
    TextView mTvBankPersonname;
    @BindView(R.id.tv_bank_name)
    TextView mTvBankName;
    @BindView(R.id.edt_bank_bank)
    EditText mEdtBankBank;
    @BindView(R.id.edt_bank_number)
    EditText mEdtBankNumber;
    @BindView(R.id.edt_bank_yzm)
    EditText mEdtBankYzm;
    @BindView(R.id.tv_bank_send)
    TextView mTvBankSend;
    @BindView(R.id.btn_bank_commit)
    AppCompatButton mBtnBankCommit;

    private boolean mIsGetInfo;
    private ArrayList<String> mBankNameList = new ArrayList<>();
    private Map<String,String> mBankMap = new HashMap<>();
    private BottomDialogManager mBottomDialogManager;
    private String mPhone;
    private String mSmsPhone;
    private String mSmsCode;
    @Override
    protected void initView() {
        super.initView();
        mToolbarName.setText("银行卡认证");
        mToolbarBack.setOnClickListener(v -> finish());

        mBottomDialogManager = new BottomDialogManager(this);
    }

    @Override
    protected void initData() {
        mPresenter.readInfo(getUserId(),getToken());

        mPresenter.getBankList();
    }

    @Override
    protected void initListener() {
        RxView.clicks(mTvBankSend)
                .throttleFirst(3, TimeUnit.SECONDS)
                .subscribe(v -> {
                    if(mIsGetInfo){
                        sendyzm();
                    }else{
                        mPresenter.readInfo(getUserId(),getToken());
                    }
                });

        mTvBankName.setOnClickListener(v -> {
            mBottomDialogManager.show();
        });
        mBottomDialogManager.setOkListener(select -> {
            mTvBankName.setText(select);
        });
        mBtnBankCommit.setOnClickListener(v -> {
            String phone = getText(mEdtBankNumber);
            String sms = getText(mEdtBankYzm);
            String bankName = getText(mTvBankName);
            String bankCard = getText(mEdtBankBank);

            if(TextUtils.isEmpty(bankCard)){
                showMessage("请填写银行卡卡号");
                return;
            }

            if(bankCard.length() < 16){
                showMessage("请填写正确的银行卡卡号");
                return;
            }

            if(TextUtils.isEmpty(bankName)){
                showMessage("请选择银行");
                return;
            }

            if(TextUtils.isEmpty(sms)){
                showMessage("请输入短信验证码");
                return;
            }


            Map<String,String> map = new HashMap<>();
            map.put(Constant.USERID, getUserId());
            map.put(UserConstant.BANK_ID, mBankMap.get(getText(mTvBankName)));
            String banknum = getText(mEdtBankBank);
            banknum = banknum.replace(" ", "");
            map.put(UserConstant.BANK_NUM, banknum);
            map.put(UserConstant.BANK_PHONE, phone);
            map.put(UserConstant.STATUS, "1");
            map.put("bankName", getText(mTvBankName));
            map.put("device", Constant.PLATFORM);
            map.put("validateCode", sms);
            mPresenter.sendService(map,AppCenter.getTokenKey(),getToken());
        });
    }

    private void sendyzm() {
        mPhone = getText(mEdtBankNumber);
        String bankcard = getText(mEdtBankBank);
        mSmsPhone = getText(mEdtBankNumber);

        if(TextUtils.isEmpty(bankcard)){
            showMessage("请输入银行卡号!");
            return;
        }

        if(bankcard.length() < 16){
            showMessage("请填写正确的银行卡卡号");
            return;
        }

        if(TextUtils.isEmpty(mPhone)){
            showMessage("请输入银行卡预留手机号!");
            return;
        }

        /**
         * 检查手机格式
         */
        if(!U.isMobileExact(mPhone)){
            showMessage("请输入正确的手机号");
            return;
        }

        mPresenter.sendyzm(mPhone,bankcard, AppCenter.getTokenKey());
    }

    @Override
    public void getBankListSuccess(HttpWrapper<List<BankBean>> wrapper) {
        if(Constant.SUCCESS_CODE.equals(wrapper.code)){
            for (BankBean bankBean : wrapper.data) {
                mBankNameList.add(bankBean.getBankName());
                mBankMap.put(bankBean.getBankName(),String.valueOf(bankBean.getBankCode()));
            }
            mBottomDialogManager.setData(mBankNameList);
        }else{
            showMessage(wrapper.getInfo());
        }
    }

    @Override
    public void getInfoSuccess(HttpWrapper<NamePhoneBean> wrapper) {
        if(Constant.SUCCESS_CODE.equals(wrapper.code)){
            try {
                if(mTvBankPersonname == null){
                    String name = U.connectString("持卡人: *",wrapper.data.getName().substring(1,wrapper.data.getName().length()));
                    mTvBankPersonname = findViewById(R.id.tv_bank_personname);
                    mTvBankPersonname.setText(name);
                }else{
                    String name = U.connectString("持卡人: *",wrapper.data.getName().substring(1,wrapper.data.getName().length()));
                    mTvBankPersonname.setText(name);
                }
            }catch (Exception e){
                mTvBankPersonname.setText("持卡人: **");
                U.errorUtil(e);
            }finally {
                mIsGetInfo = true;
            }
        }else{
            getInfoFailed(wrapper);
        }
    }

    public void getInfoFailed(HttpWrapper<NamePhoneBean> wrapper) {
        if (Constant.TOKEN_TIMEOUT.equals(wrapper.code)){
            U.tokenOut(this);
            mIsGetInfo = false;
        }else{
            Logger.i(wrapper.info);
            mIsGetInfo = false;
        }
    }


    @Override
    public void sendServiceSuccess(HttpWrapper<String> bean) {
        if(Constant.SUCCESS_CODE.equals(bean.code)){
            showMessage(bean.getInfo());
            sendSuccess(bean);
        }else if(Constant.ERROR_CODE.equals(bean.code)){
            if (TextUtils.isEmpty(bean.data)) {
                showMessage(bean.info);
                return;
            }

            U.getSingleDialog(this,"温馨提示",bean.getInfo(),"确定",null).show();
        }else if(Constant.BQSLOSE_CODE.equals(bean.code)){
            U.toDrainage(this, DrainageActivity.TYPE_REFUSE,Constant.REFUES);
        }else if(Constant.TOKEN_TIMEOUT.equals(bean.code)){
            U.tokenOut(this);
        }else{
            showMessage(bean.getInfo());
        }
    }

    @Override
    public void sendSmsSuccess(HttpWrapper<Single> bean) {
        if(Constant.SUCCESS_CODE.equals(bean.code)){
            time();
        }else if(Constant.BQSLOSE_CODE.equals(bean.getCode())){
            U.showDialogJuJue(this,Constant.REFUES);
        }else{
            showMessage(bean.getInfo());
        }
    }

    public void sendSuccess(HttpWrapper<String> bean) {
        Logger.i(bean.code);
        mPresenter.router(this);
    }

    @Override
    public void time() {
        showMessage("成功发送验证码");
        mTvBankSend.setEnabled(false);
        addSubscription(U.countdownFlowable(59)            //倒计时60秒
                .subscribe(
                        time -> mTvBankSend.setText("重新发送" + "(" + time + ")"),    //每秒赋值
                        U::errorUtil,             //提示错误信息
                        () -> {
                            mTvBankSend.setEnabled(true);
                            mTvBankSend.setText(getString(R.string.reSendyzm));
                        }));
    }


    @Override
    protected int getLayoutId() {
        return R.layout.activity_bankcard;
    }

    @Override
    protected void initInject() {
        getActivityComponent().inject(this);
    }
}
